<?php

namespace App\Http\Controllers\Admin;

use App\Model\Permission;
use App\Model\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $role = Role::paginate(10);
        foreach ($role as $v){
            $v = $v->permission;
        }
        return view('admin.role.list',compact('role'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //获取权限数据
        $permission = Permission::get();
        return view('admin.role.role_add',compact('permission'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->except('_token');
//       1.数据合法性验证
        $rule = [
            'role_name' => 'required'
        ];
        $messages = [
            'role_name.required' => '角色名称不能为空!'
        ];

        $validator = Validator::make($request->all(),$rule,$messages);
        if($validator->fails()){
            $errors = $validator->errors()->toArray();
            $res = [
                'status'=>1,
                'data'=>$errors,
                'message'=>'验证失败'
            ];
            return json_encode($res);
        }
        //保存数据到数据库
        $role = new Role();
        //判断角色数据是否已经存在
        $userinfo = $role->where('role_name',$input['role_name'])->first();
        if(!empty($userinfo)){
            $res = [
                'status'=>1,
                'data'=>['角色数据已经存在！'],
                'message'=>'添加失败'
            ];
            return json_encode($res);
        }
        $role->role_name = $input['role_name'];
        $status = $role->save();

        if($status){
            //判断书否选择了权限 并插入权限
            if(isset($input['roleid'])){
                $role_per = [];
                foreach ($input['roleid'] as $v){
                    $role_per[] = [
                        'role_id'=>$role->id,
                        'permission_id' => $v
                    ];
                }
                DB::table('role_permission')->insert($role_per);
            }
            $res = [
                'status'=>0,
                'data'=>[],
                'message'=>'添加成功'
            ];
        }else{
            $res = [
                'status'=>1,
                'data'=>['添加失败，请检查数据库'],
                'message'=>'添加失败'
            ];
        }
        return json_encode($res);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //通话id 获取数据信息
        $role = Role::find($id);
        //获取权限数据
        $permission = Permission::get();
        //获取角色拥有的数据
        $own_per = $role->permission;
        $own_perid = [];
        foreach ($own_per as $v){
            $own_perid[] = $v->id;
        }
        return view("admin.role.role_edit",compact('role','permission','own_perid'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->except('_token');
//        Log::info($id);
//        1.数据合法性验证
        $rule = [
            'role_name' => 'required'
        ];
        $messages = [
            'role_name.required' => '角色名称不能为空!'
        ];

        $validator = Validator::make($request->all(),$rule,$messages);
        if($validator->fails()){
            $errors = $validator->errors()->toArray();
            $res = [
                'status'=>1,
                'data'=>$errors,
                'message'=>'验证失败'
            ];
            return json_encode($res);
        }
        //修改角色名称
        $role = Role::find($id);
        $role->role_name = $input['role_name'];
        $status = $role->save();
        if($status){
            //修改角色权限中间表数据
            DB::table('role_permission')->where('role_id',$id)->delete();
            if(isset($input['perid'])){
                $role_per = [];
                foreach ($input['perid'] as $v){
                    $role_per[] = [
                        'role_id'=>$role->id,
                        'permission_id' => $v
                    ];
                }
                $in_status = DB::table('role_permission')->insert($role_per);
                if($in_status){
                    $res = [
                        'status'=>0,
                        'data'=>[],
                        'message'=>'修改成功'
                    ];
                }else{
                    $res = [
                        'status'=>1,
                        'data'=>['权限中间表插入失败'],
                        'message'=>'权限中间表插入失败'
                    ];
                }
            }else{
                $res = [
                    'status'=>0,
                    'data'=>[],
                    'message'=>'修改成功'
                ];
            }
        }else{
            $res = [
                'status'=>1,
                'data'=>['修改失败，请检查数据!'],
                'message'=>'修改失败'
            ];
        }
        return json_encode($res);


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    //修改用户状态
    public function checkStatus(Request $request){
        $input = $request->except('_token');
        $role = new Role();
        $status = $role->where('id',$input['id'])->update(['status'=>$input['status']]);
        if($status){
            $res = [
                'status'=>0,
                'data'=>[],
                'message'=>'修改成功'
            ];

        }else{
            $res = [
                'status'=>1,
                'data'=>['修改失败！'],
                'message'=>'修改失败'
            ];
        }
        return json_encode($res);
    }
    //批量删除
    public function deleteAll(Request $request){
        $role = new Role();
        $status = $role->whereIn('id',$request->get('ids'))->delete();
        if($status){
            $res = [
                'status'=>0,
                'data'=>[],
                'message'=>'批量删除成功'
            ];

        }else{
            $res = [
                'status'=>1,
                'data'=>['批量删除失败！'],
                'message'=>'批量删除失败'
            ];
        }
        return json_encode($res);
    }
}
